package cn.zzuli.anew;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PlayService extends Service {
    private MediaPlayer mp;
    private List<Music> musicList;
    private int cur_pos = 0;


    public PlayService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    public void onCreate() {
        musicList = getMusic();
        mp = new MediaPlayer();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                next();
            }
        });
    }

    private List<Music> getMusic() {
        List<Music> musics = new ArrayList<>();
        String[] projection = {
                MediaStore.Audio.Media._ID,//歌曲的id
                MediaStore.Audio.Media.TITLE,//歌曲的名称
                MediaStore.Audio.Media.ARTIST,//歌手名
                MediaStore.Audio.Media.DURATION,//歌曲的播放时长
                MediaStore.Audio.Media.DATA,//歌曲文件的路径
                MediaStore.Audio.Media.ALBUM_ID,//专辑名
                MediaStore.Audio.Media.SIZE//歌曲文件的大小
        };
        Cursor cursor = getContentResolver(). query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        while (cursor.moveToNext()) {
            int _id = cursor.getInt(Integer.parseInt("0"));
            String title = cursor.getString(1);
            String artist = cursor.getString(2);
            long duration = cursor.getLong(3);
            String data = cursor.getString(4);
            int album_id = cursor.getInt(Integer.parseInt("5"));
            int size = cursor.getInt(Integer.parseInt("6"));
            System.out.println(_id + "," + title + "," + artist + "," + duration + "," + data + "," + album_id + "," + size);
            musics.add(new Music(_id, title, artist, duration, data, album_id, size));
        }
        cursor.close();
        return musics;
    }

    private void next() {
        ++cur_pos;
        if (cur_pos == musicList.size())
            cur_pos = 0;
        play(cur_pos);
    }
    private void previous() {
        --cur_pos;
        if (cur_pos == -1)
            cur_pos = musicList.size() - 1;
        play(cur_pos);

    }

    private void play(int position) {

        try {
            mp.reset();
            mp.setDataSource(musicList.get(position).getData());
            mp.prepare();
            mp.start();
            cur_pos = position;

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}